//
//  AppDelegate.m
//  YYPHSpeedJump
//
//  Created by sujiang on 15/12/15.
//  Copyright © 2015年 sujiang. All rights reserved.
//

#import "AppDelegate.h"
#import "OnceViewController.h"
#import "HomeViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "RootViewController.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"
#import "UMSocialSinaSSOHandler.h"
#import "UMessage.h"
#import "Reachability.h"
@interface AppDelegate ()<WXApiDelegate>

    

@end

@implementation AppDelegate

- (void)removeHeaderAndFooterFromView:(UIView *)view
{
    if ([view isKindOfClass:[MJRefreshNormalHeader class]] || [view isKindOfClass:[MJRefreshAutoNormalFooter class]]) {
        MJRefreshNormalHeader *headr = (MJRefreshNormalHeader *)view;
        [headr endRefreshing];
        return;
    } else {
        for (UIView *bView in view.subviews) {
            [self removeHeaderAndFooterFromView:bView];
        }
    }
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [NSThread sleepForTimeInterval:2.0f];
    [self setRootVC];
    [self.window makeKeyAndVisible];
    //消息推送
    [self requestData];
     [self addUMSocial];
    [UMessage startWithAppkey:@"5699e81567e58e7cba000b92" launchOptions:launchOptions];
    [WXApi registerApp:@"wxa97033b65142f1e6" withDescription:@"速降"];
   
   // [Tools shareManager].status = YES;
    // Override point for customization after application launch
    
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        /**
         *  AFNetworkReachabilityStatusUnknown          = -1,
         AFNetworkReachabilityStatusNotReachable     = 0,
         AFNetworkReachabilityStatusReachableViaWWAN = 1,
         AFNetworkReachabilityStatusReachableViaWiFi = 2,
         */
        if (status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable) {
            [NetworkHandle addToWindow];
            self.window.userInteractionEnabled = NO;
            
        } else {
            [Tools shareManager].status = YES;
            [NetworkHandle removeFromWindow];
            [self removeHeaderAndFooterFromView:self.window];
            self.window.userInteractionEnabled = YES;
        }

        
    }];
    
    
    
    return YES;
}
- (void)requestData
{
    //公共资源
    NSString *propertyUrl = [NSString stringWithFormat:@"%@%@",kBaseUrl,kPropertyUrl];
    [NetworkHandle getPropertyUrl:propertyUrl dict:nil success:^(NSDictionary *dictionary) {
        self.PModel = dictionary[@"PModel"];
        [[NSUserDefaults standardUserDefaults]setObject:self.PModel.share_word forKey:@"share_word"];
        [[NSUserDefaults standardUserDefaults]setObject:self.PModel.share_url forKey:@"share_url"];
        [[NSUserDefaults standardUserDefaults]setObject:self.PModel.update forKey:@"update"];
        [[NSUserDefaults standardUserDefaults]setObject:self.PModel.showAlert forKey:@"showAlert"];
    }];
}

// 友盟分享
- (void)addUMSocial
{
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    // NSLog(@"version = %@",version);
    //友盟统计
    [MobClick setAppVersion:version];
    //友盟设置APPKey
    [UMSocialData setAppKey:@"5699e81567e58e7cba000b92"];
    
    //友盟分享微信
    [UMSocialWechatHandler setWXAppId:@"wxa97033b65142f1e6" appSecret:@"ec963ae476f627786f59aa24d424f824" url:@"https://itunes.apple.com/cn/app/su-jiang/id938064496?mt=8"];
    //友盟分享QQ
    [UMSocialQQHandler setQQWithAppId:@"1105011199" appKey:@"GaJeVop59L6H9O6M" url:@"https://itunes.apple.com/cn/app/su-jiang/id938064496?mt=8"];
    //友盟开始统计
    [MobClick startWithAppkey:@"5699e81567e58e7cba000b92" reportPolicy:BATCH   channelId:nil];
    //友盟分享新浪微博
    [UMSocialSinaSSOHandler openNewSinaSSOWithAppKey:@"3921700954" RedirectURL:@"http://sns.whalecloud.com/sina2/callback"];

    
    //消息推送判断版本
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= _IPHONE80_
    if(UMSYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0 ") != NSOrderedAscending)

    {
        //register remoteNotification types （iOS 8.0及其以上版本）
        UIMutableUserNotificationAction *action1 = [[UIMutableUserNotificationAction alloc] init];
        action1.identifier = @"action1_identifier";
        action1.title=@"Accept";
        action1.activationMode = UIUserNotificationActivationModeForeground;//当点击的时候启动程序
        
        UIMutableUserNotificationAction *action2 = [[UIMutableUserNotificationAction alloc] init];  //第二按钮
        action2.identifier = @"action2_identifier";
        action2.title=@"Reject";
        action2.activationMode = UIUserNotificationActivationModeBackground;//当点击的时候不启动程序，在后台处理
        action2.authenticationRequired = YES;//需要解锁才能处理，如果action.activationMode = UIUserNotificationActivationModeForeground;则这个属性被忽略；
        action2.destructive = YES;
        
        UIMutableUserNotificationCategory *categorys = [[UIMutableUserNotificationCategory alloc] init];
        categorys.identifier = @"category1";//这组动作的唯一标示
        [categorys setActions:@[action1,action2] forContext:(UIUserNotificationActionContextDefault)];
        
        UIUserNotificationSettings *userSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert
                                                                                     categories:[NSSet setWithObject:categorys]];
        [UMessage registerRemoteNotificationAndUserNotificationSettings:userSettings];
        
    } else{
        //register remoteNotification types (iOS 8.0以下)
        [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeAlert];
    }
#else
    
    //register remoteNotification types (iOS 8.0以下)
    [UMessage registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeSound];
    
#endif
    //for log
    [UMessage setLogEnabled:YES];
    [UMessage setBadgeClear:NO];
    [NSCharacterSet characterSetWithCharactersInString:@"<>"];
    // NSString *tokenString = [token stringByReplacingOccurrencesOfString:@""withString:@""];
}
- (void)setRootVC
{
     // [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"default_login"];
    if (![[NSUserDefaults standardUserDefaults] valueForKey:@"default_login"]) {
        HomeViewController *homeVC = [[HomeViewController alloc] init];
        self.window.rootViewController = homeVC;
    } else {
        RootViewController *rootVC = [[RootViewController alloc] init];
        self.window.rootViewController = rootVC;
    }
    
    if (![[NSUserDefaults standardUserDefaults] valueForKey:@"isFirst"]) {
        OnceViewController *onceVC = [[OnceViewController alloc] init];
        self.window.rootViewController = onceVC;
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isFirst"];
    }
 
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    
    //跳转支付宝钱包进行支付，处理支付结果
    
//    
//    NSString *urlStr=[[url absoluteString] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    NSString *wxORwb = [urlStr substringToIndex:2];
//    NSLog(@"%@",wxORwb);

//    
//    BOOL isSuc = [WXApi handleOpenURL:url delegate:[WXPayManager shareManager]];
//    return  isSuc;
    
    BOOL result = [UMSocialSnsService handleOpenURL:url];
    if (result == FALSE) {
        //调用其他SDK，例如支付宝SDK等
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
        }];
    }
    return result;
    
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
   //return  [WXApi handleOpenURL:url delegate:[WXPayManager shareManager]];
     return  [UMSocialSnsService handleOpenURL:url];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"didFailToRegisterForRemoteNotificationsWithError:%@", [error localizedDescription]);
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [UMessage registerDeviceToken:deviceToken];

    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    NSString *deviceToken1 = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    
   // NSLog(@"deviceToken:%@", deviceToken1);
}


- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return UIInterfaceOrientationMaskPortrait;
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [[NSNotificationCenter defaultCenter] postNotificationName:@"EnterForeground" object:nil userInfo:nil ];
    
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "com.speedjump.YYPHSpeedJump" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"YYPHSpeedJump" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"YYPHSpeedJump.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end
